#! user/bin/env python
# -*- coding:utf-8 -*-

import requests
import http.cookiejar
import lxml
import re
import time
import os.path
import json
import matplotlib.pyplot as plt
from PIL import Image
from bs4 import BeautifulSoup

# make request header
url = 'https://www.zhihu.com/'
loginUrl = 'https://www.zhihu.com/login/email'
captchaImgUrl = url + 'captcha.gif?r=' + str(int(time.time() * 1000)) + '&type=login&lang=cn'

headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87\
                  Safari/537.36',
    "Referer": "https://www.zhihu.com/",
    "Host": "www.zhihu.com"
}

proxies = {
    "http": "http://fwx405548:fc@19930207@proxy.huawei.com:8080",
    "https": "https://fwx405548:fc@19930207@proxy.huawei.com:8080",
}

cookie = 'cookies.txt'
session = requests.Session()
if os.path.exists(cookie):
    try:
        session.cookies = http.cookiejar.MozillaCookieJar(cookie)
        session.cookies.load(ignore_discard=True)
        print("load cookie succeed")
    except:
        print("cookie load faild")
else:
    print("cookie not exised")


def _getXsrf():
    """
    get xsrf and captcha for login, return a tumple.
    :return:(xsrf, captcha) 
    """
    response = session.get(loginUrl, headers=headers, proxies=proxies)
    soup = BeautifulSoup(response.text, 'lxml')
    xsrf = soup.input['value']
    return xsrf


def _getCaptcha():
    r = session.get(captchaImgUrl, headers=headers, proxies=proxies)
    with open('captcha.gif', 'wb') as f:
        f.write(r.content)
    im = Image.open('captcha.gif').resize((200, 44))
    plt.imshow(im)
    _pos = plt.ginput(2)
    pos = list()
    for i in _pos:
        _x, _y = i
        x = round(float(_x), 3)
        y = round(float(_y), 4)
        pos.append([x,y])
    captcha = {
        'img_size': [200, 44],
        'input_points': pos
    }
    return captcha



def login(username, passwd):
    """
    :param username: zhihu username 
    :param passwd: zhihu passwd
    :return: 
    """

    #  select login ways, email or phone

    if re.match(r'^\d+$', username):
        print("use phone to login...")
    else:
        print("use email to login...")
        xsrf = _getXsrf()
        data = {
            '_xsrf': xsrf,
            'password': passwd,
            'email': username,
            'captcha_type': 'cn'
        }
        print("make data succeed")
    # try:
    #     response = session.post(loginUrl, data=data, headers=headers, proxies=proxies)
    #     print(response.text)
    # except:
    print("try to get captcha...")
    data['captcha'] = _getCaptcha()
    print("begin to login...")
    result = session.post(loginUrl, data=data, headers=headers, proxies=proxies)
    print(result.text)


username = 'fc896745130@163.com'
passwd = 'fc19930207'
login(username, passwd)
